package cn.itsource.service.impl;

import cn.itsource.Utils.UseTools;
import cn.itsource.domain.BlogArticle;
import cn.itsource.mapper.BlogArticleMapper;
import cn.itsource.query.BaseQuery;
import cn.itsource.service.IBlogArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class BlogArticleServiceImpl implements IBlogArticleService {

    /**
     * 注入持久层依赖
     */
    @Autowired
    private BlogArticleMapper mapper;

    @Override
    public PageInfo<BlogArticle> getAllArticleByPage(BaseQuery query) {
//        // 1. 调用分页插件分页
//        PageHelper.startPage(query.getPage(),query.getRows());
//        // 2. 调用查询的方法
//        List<BlogArticle> articleList = mapper.getAllArticle(query);
//        // 3. 使用分页插件封装分页数据
//        PageInfo<BlogArticle> pageInfo = new PageInfo<>(articleList);
//        // 4. 将分页的数据返回回去
//        return pageInfo;
        PageHelper.startPage(query.getPage(),query.getRows());
        List<BlogArticle> allArticle = mapper.getAllArticle(query);
        PageInfo<BlogArticle> blogArticlePageInfo = new PageInfo<>(allArticle);
        return blogArticlePageInfo;
    }

    @Override
    public BlogArticle getbolgByid(Long id) {
        return mapper.getbolgByid(id);
    }

    @Override
    public void deleteArticleById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(BlogArticle article, HttpServletRequest request) {
        // 设置修改事件
        article.setUpdateTime(new Date());
        if (article.getId() == null) {
            // 获取当前登录用户的id
            Long userId = UseTools.getCurrentUserId(request);
            // 将用户id设置进行article实体类
            article.setUserId(userId);
            // 如果id为空，就是新增
            mapper.insertSelective(article);
        } else {
            // 如果id不为空，就是修改
            mapper.updateByPrimaryKeySelective(article);
        }
    }

    @Override
    public void batchDelete(BaseQuery query) {
        mapper.batchDelete(query.getIds());
    }
}
